/*
 * @Author: zhangyang
 * @Date: 2022-03-09 10:07:43
 * @LastEditTime: 2022-05-30 15:53:33
 * @Description: 用户头像下拉菜单相关
 */
import { loginOut } from '@/api/base';
import { removeToken, useNavStore } from '@/stores';

import CarbonEdit from '~icons/carbon/edit';
import LucidePower from '~icons/lucide/power';

import { NForm, NFormItem, NInput } from 'naive-ui';

import type { DropdownOption, FormInst, FormRules } from 'naive-ui';
import type { CSSProperties } from 'vue';
import type { Router } from 'vue-router';
import Msg from '../Msg';
import { useMsgStore } from '@/stores/msg';
import { modifyPassword } from '@/api/user';

type Form = {
  old_pwd: string;
  pwd: string;
  pwd_again: string;
};

const useForm = () => {
  const form = ref<Form>({
    old_pwd: '',
    pwd: '',
    pwd_again: ''
  });
  const formRef = ref<FormInst>();

  const rules: FormRules = {
    old_pwd: [{ required: true, trigger: 'blur', message: '请输入旧密码' }],
    pwd: [{ required: true, trigger: 'blur', message: '请输入新密码' }],
    pwd_again: [
      { required: true, trigger: 'blur', message: '请再次输入新密码' },
      { trigger: 'blur', validator: (rule, value) => form.value.pwd === value, message: '两次输入的密码不一致' }
    ],
  };
  return { form, formRef, rules };
};

export const setDialogCenter = (ext: CSSProperties = {}): CSSProperties => {
  return {
    position: 'absolute',
    top: '10vh',
    left: '50%',
    transform: 'translateX(-50%)',
    ...ext
  };
};

const useMod = (router: Router) => {
  const { form, rules, formRef } = useForm();

  const submitForm = async () => new Promise((resolve) => {
    formRef.value?.validate(async (err) => {
      if (!err) {
        resolve(true);
        await modifyPassword(form.value.old_pwd, form.value.pwd);
        window.$alert.info({
          title: '提示',
          content: '密码修改成功，请重新登录！',
          closable: false,
          'mask-closable': true,
          'positive-text': '确认',
          onPositiveClick: () => {
            removeToken();
            router.push({ name: 'base-login' });
          }
        }).style = setDialogCenter();
      } else {
        resolve(false);
      }
    });
  });

  const renderPwdIetm = (path: keyof Form, placeholder: string) => {
    return h(NFormItem, { path }, {
      default: () => h(NInput, {
        value: form.value[path],
        onUpdateValue: (v) => form.value[path] = v,
        placeholder,
        clearable: true,
        type: 'password',
        showPasswordOn: 'click',
        onKeyup: (e) => {
          if (e.key.toLowerCase() === 'enter') {
            submitForm();
          }
        }
      })
    });
  };

  const renderMod = () => h(NForm, {
    model: form.value,
    rules,
    ref: formRef
  }, {
    default: () => [
      renderPwdIetm('old_pwd', '请输入旧密码'),
      renderPwdIetm('pwd', '请输入新密码'),
      renderPwdIetm('pwd_again', '请再次输入新密码')
    ]
  });

  const modHandler = () => {
    window.$alert.info({
      title: '修改密码',
      content: renderMod,
      'negative-text': '取消',
      'positive-text': '确认',
      onPositiveClick: submitForm
    }).style = setDialogCenter();
  };

  return { modHandler };
};

export const useMenu = () => {
  const router = useRouter();
  const { modHandler } = useMod(router)
  
  const options: DropdownOption[] = [
    { label: '修改密码', key: 'modify', icon: () => h(CarbonEdit) },
    { label: '退出登录', key: 'logout', icon: () => h(LucidePower) }
  ];

  const optionHandler = async (key: string | number) => {
    switch (key) {
      case 'logout':
        await loginOut();
        const { RoleRoute } = storeToRefs(useNavStore());
        RoleRoute.value = [];
        removeToken();
        router.push({ name: 'base-login' });
        break;
    
      case 'modify':
        modHandler();
        break;
      default:
        break;
    }
  };

  return {
    options,
    optionHandler
  };
};

export const useMsg = () => {
  const hasUnreadMessage = ref(true);

  const readMessage = (...e: any) => {
    console.log('读消息');
    hasUnreadMessage.value = false;
  };

  const messages = () => {
    const state = useMsgStore();
    return h(Msg,
      {
        list: state.msgList,
        onDel: (index: number) => {
          console.log(index)
          state.msgList.splice(index, 1);
        }
      },
    );
  };

  return {
    hasUnreadMessage,
    messages,
    readMessage
  };
}